# -*- coding:utf-8 -*-
# 作者：mushroom
# E-Mail : linzhanyu@gmail.com

# 抓取网页的内容

import re

class HtmlText :
    coding = 'utf-8'

class HtmlPictrue:
    coding = None

# 定义各种不同的关键字,找到了就尝试用不同的算法来匹配
# 这是一个美好的愿望
dict_flags = {  'host':[u'地址',],
                'port':[u'端口',],
                'username':[u'用户名', ],
                'password':[u'密码', ],
                }
def GetKey( val ):
    for k, v in dict_flags.iteritems():
        if val in v:
            return k
    return None

class html_xinm (HtmlText):
    url = 'http://xinm.tk/free.html'        # 这个链接已经变了
    url = 'aHR0cDovL3d3dy54aW5tLnRrL2ZyZWUucGhw'

    def parse(self, content):
        """
        从网页内容中分析出用户名，密码，地址，端口
        参数 : content UNICODE 编码的网页内容
        """
        regex = re.compile(u'[：:]\s*([^</"]{8,})', re.UNICODE)
        regex = re.compile(u'[：:]([^<]*)', re.UNICODE)
        tag_beg = '<p>'
        tag_end = '</p>'
        self.flags = [u'地址', u'端口', u'用户名', u'密码', ]
        result = []
        idx_beg = content.find(tag_beg)

        d = {'host':None, 'port':22, 'username':None, 'password':None, }

        fix = []
        while idx_beg != -1 :
            idx_end = content.find(tag_end, idx_beg)
            sub_content = content[idx_beg+len(tag_beg):idx_end]
            # print '='*30, 'Begin'
            # print sub_content
            # print '='*30, 'End'
            record = False
            for i in range(4):
                flag = self.flags[i]
                findIdx = sub_content.find( flag )
                if -1 != findIdx :
                    bIdx =findIdx + len(flag)
                    subText = sub_content[bIdx:]
                    result = regex.search( subText )
                    if result != None :
                        val = result.group(1)
                        val = val.strip('\n ')
                        # print flag, ':', val
                        k = GetKey(flag)
                        if k != None:
                            d[k] = val
                            record = True

            idx_beg = content.find(tag_beg, idx_end)

            if not record:
                continue
            for k, v in d.iteritems() :
                if v == None :
                    record = False
                    break
            if record :
                fix.append( d.copy() )

        return fix

class html_usassh (HtmlText):
    # url = 'https://www.usassh.com/free.php'
    url = 'aHR0cHM6Ly93d3cudXNhc3NoLm5ldC9mcmVlLnBocA=='
    def __init__(self):
        self.regex = re.compile(u'>([^<]+)<\/')
        self.flags = [u'SSH服务器：', u'ssh端口：', u'SSH帐号：', u'SSH密码：']
    def parse(self, content):
        result = {}
        lines = content.split('\n')
        for line in lines:
            findRet = self.regex.search( line )
            if findRet != None :
                rTable = re.compile(u'>([^<]+)<')
                findTitle = rTable.search(line)
                if findTitle != None:
                    title = findTitle.group(1)
                    # title = title.encode('utf-8')
                    # print title, type(title)
                    if title in self.flags:
                        result[title] = findRet.group(1)
        print '-'*50
        for k, v in result.items():
            print k, ' = ', v
        fix = []
        d = {}
        d['host']       = result[u'SSH服务器：']
        d['port']       = result[u'SSH端口：']
        d['username']   = result[u'SSH帐号：']
        d['password']   = result[u'SSH密码：']
        fix.append(d)
        return fix

class html_lovessh (html_usassh):
    # url = 'https://www.lovessh.com/client/free.php'
    url = 'aHR0cDovL3d3dy5sb3Zlc3NoLmNvbS9jbGllbnQvZnJlZS5waHA='
    def __init__(self):
        html_usassh.__init__( self )
        self.regex = re.compile(u'^<[^!]+>([^<]+)<\/')
        self.flags = [u'SSH服务器：', u'SSH服务器：', u'SSH端口：', u'SSH帐号：', u'SSH密码：']
    pass

class html_unssh (HtmlPictrue):
    url = 'http://49.212.195.249/onlybird.php'
    def parse(self, content):
        # print content
        return None

# 'aHR0cHM6Ly9ibHVlc3NoLmNvbS9jb250ZW50L2ZyZWVzc2gv'        # 一个带图形密码的免费地址
# 'aHR0cDovL3d3dy5ob3N0enp6LmNvbS9zc2gvc2VydmVycy54bWw='    # usassh & lovessh

# ssh_issus = [html_usassh, html_lovessh, html_xinm]
# ssh_issus = [html_lovessh, html_xinm, ]
ssh_issus = [html_xinm, ]
# Test html
# ssh_issus = [html_unssh]

